package com.agv.web.security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.agv.core.objectDomain.Usuario;

public class SecurityFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		String requestedUri = ((HttpServletRequest) request).getRequestURI();

		if (requestedUri.contains("agvLogin.do")
				|| requestedUri.contains("agvLoginCmd.do")
				|| requestedUri.contains(".css")
				|| requestedUri.contains(".png")
				|| requestedUri.contains(".js")
				|| requestedUri.contains(".jpeg")
				|| requestedUri.contains(".jpg")
				|| requestedUri.contains("login.jsp")
				|| requestedUri.equals("/agvWeb") 
				|| requestedUri.equals("/agvWeb/")) {
			chain.doFilter(request, response);
			return;
		}

		boolean authorized = false;
		if (request instanceof HttpServletRequest) {
			HttpSession session = ((HttpServletRequest) request)
					.getSession(false);
			if (session != null) {
				Usuario user = (Usuario) session.getAttribute("usuarioObj");
				if (user != null)
					authorized = true;
			}
		}

		if (authorized) {
			chain.doFilter(request, response);
			return;
		} else {
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("pages/login.jsp");
			request.setAttribute("sinSesion", "si");
			dispatcher.forward(request, response);
			return;
		}

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
